import React, { useState } from 'react';
import Web3 from 'web3';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import FormData from 'form-data';
import { Rate, Upload, Button, message } from 'antd';
import { UploadOutlined, ArrowUpOutlined } from '@ant-design/icons';
import UserListABI from '../contract/ABIs/UserList.json';
import MarketplaceABI from '../contract/ABIs/Marketplace.json';
import UserABI from '../contract/ABIs/User.json';
import MaterialListAddr from '../contract/ADDRESSes/MaterialListAddr';
import UserListAddr from '../contract/ADDRESSes/UserListAddr';
import './SubmitReview.css';

const JWT = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mb3JtYXRpb24iOnsiaWQiOiJiODVmNDg2OC0yNWZlLTRkZWItOGUxOS1iYTZhYjg4ZmUyOGIiLCJlbWFpbCI6Im1laXp6aWxhaWNoaW5nNDUxQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaW5fcG9saWN5Ijp7InJlZ2lvbnMiOlt7ImlkIjoiRlJBMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfSx7ImlkIjoiTllDMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfV0sInZlcnNpb24iOjF9LCJtZmFfZW5hYmxlZCI6ZmFsc2UsInN0YXR1cyI6IkFDVElWRSJ9LCJhdXRoZW50aWNhdGlvblR5cGUiOiJzY29wZWRLZXkiLCJzY29wZWRLZXlLZXkiOiIzYjdlMmZlYTQwOTA2NjY4NTAyZCIsInNjb3BlZEtleVNlY3JldCI6IjAzNWUyZTRiZTM2NDg0NTFmYzFkOTRkMzhjNmRkMTJhMWVmMjEyYTM4YzJhYmE4OWNmMjNiNjk4NTkwMTg1NzkiLCJpYXQiOjE3MTgzMzE5Mzh9.dSVuazN5PYS9152mG4op-ugWX9rsAWRMbdYv5PmZeg8';
const pinFileToIPFS = async (file) => {
    const formData = new FormData();
    formData.append('file', file);

    const pinataMetadata = JSON.stringify({
        name: 'File name',
    });
    formData.append('pinataMetadata', pinataMetadata);

    const pinataOptions = JSON.stringify({
        cidVersion: 0,
    });
    formData.append('pinataOptions', pinataOptions);

    try {
        const res = await axios.post("https://api.pinata.cloud/pinning/pinFileToIPFS", formData, {
            maxBodyLength: "Infinity",
            headers: {
                'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
                'Authorization': `Bearer ${JWT}`
            }
        });
        return res.data.IpfsHash;
    } catch (error) {
        console.log(error);
        throw new Error('Failed to upload file to IPFS');
    }
};

const ProductReport = () => {
    const { userAddr, productid } = useParams();
    // const [rating, setRating] = useState(0);
    const [comment, setComment] = useState('');
    const [image, setImage] = useState(null);
    const [preview, setPreview] = useState(null);

    const web3 = new Web3(window.ethereum);
    const marketplaceContract = new web3.eth.Contract(MarketplaceABI, MaterialListAddr);

    const handleImageUpload = async (file) => {
        try {
            const ipfsHash = await pinFileToIPFS(file);
            console.log("ipfsHash", ipfsHash);
            return ipfsHash;
        } catch (error) {
            console.error('图片上传失败', error);
        }
    };

    const submitReview = async () => {
        try {
            const accounts = await web3.eth.requestAccounts();
            const ipfsHash = image ? await handleImageUpload(image) : '';
            console.log("productid, rating, comment, ipfsHash", productid, comment, ipfsHash);
            await marketplaceContract.methods.reportProduct(productid, comment, ipfsHash).send({ from: accounts[0] });
            alert('举报提交成功');
        } catch (error) {
            console.error('举报提交失败', error);
        }
    };

    const beforeUpload = (file) => {
        setImage(file);
        setPreview(URL.createObjectURL(file)); // 设置预览 URL
        return false; // 防止自动上传
    };

    const handleChange = (info) => {
        if (info.file.status === 'done') {
            message.success(`${info.file.name} 文件上传成功`);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 文件上传失败`);
        }
    };

    return (
        <div className="review-container">
            <h2>举报</h2>
            {/* <Rate
                value={rating}
                onChange={setRating}
                allowHalf
                style={{ fontSize: '24px' }}
            /> */}
            <textarea
                className="review-comment"
                placeholder="评论"
                value={comment}
                onChange={(e) => setComment(e.target.value)}
            />
            <Upload.Dragger
                beforeUpload={beforeUpload}
                onChange={handleChange}
                showUploadList={false}
                className="upload-dragger"
            >
                <p className="ant-upload-drag-icon">
                    <ArrowUpOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
                </p>
                <p className="ant-upload-text">点击或拖拽文件到此区域进行上传</p>
            </Upload.Dragger>
            {preview && (
                <div className="image-preview">
                    <img src={preview} alt="Image Preview" />
                </div>
            )}
            <button onClick={submitReview} className="review-submit-button">提交</button>
        </div>
    );
};

export default ProductReport;